package com.itheima.reggie.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器
 * 功能：能对公共字段进行自动填充，避免重复的代码开发
 * 简化了工作
 * 使用时需在实体类对象需要自动填充的属性上加上@TableField注解
 */

@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {

    @Autowired
    private HttpServletRequest request;

    /**
     * 插入时，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        System.out.println(empId);
        metaObject.setValue("createTime",LocalDateTime.now());
        metaObject.setValue("updateTime",LocalDateTime.now());
        metaObject.setValue("createUser",BaseContext.getCurrentId());
        metaObject.setValue("updateUser",BaseContext.getCurrentId());

    }

    /**
     * 更新时，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser",BaseContext.getCurrentId());
    }
}
